首页/ 学科题库/ vite/ TypeScript 配置优化
vite 实战教程

TypeScript 配置优化

2026-05-23 约 6 分钟 juanwangdev

TypeScript 配置优化

Vite 与 TypeScript 需要正确配置才能协同工作,确保路径解析和类型检查一致。

基础 tsconfig.json

JSON
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "skipLibCheck": true,

    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,

    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}

路径别名同步

JavaScript
// vite.config.js
export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})
JSON
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

注意:别名配置需在 vite.config.js 和 tsconfig.json 中同步设置。

关键配置项

配置项值说明
moduleResolutionbundlerVite 模块解析方式
isolatedModulestrue每个文件作为独立模块
allowImportingTsExtensionstrue允许导入 .ts 文件

引用 Vite 类型

JSON
{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}

或使用三斜线指令:

TypeScript
/// <reference types="vite/client" />

配置分离

JSON
tsconfig.json          # 主配置
tsconfig.node.json     # Node 端配置(vite.config.ts)
text
// tsconfig.json
{
  "references": [
    { "path": "./tsconfig.node.json" }
  ]
}

// tsconfig.node.json
{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "bundler"
  },
  "include": ["vite.config.ts"]
}

要点总结

  • moduleResolution 设为 bundler
  • 路径别名需同步配置
  • 引用 vite/client 类型声明
  • 使用 references 分离 Node 配置
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 强制重新预构建 下一篇 → 类型检查策略